package
{
	import model.CategoryVO;
	import model.ProjectVO;
	import model.TaskVO;
	
	import mx.collections.ArrayCollection;
	import mx.utils.ArrayUtil;
	
	public class LocalData
	{
		// list of all projects
		[Bindable]
		public var projects:ArrayCollection = new ArrayCollection();
		// list of all categories
		[Bindable]
		public var categories:ArrayCollection = new ArrayCollection();
		// list of all tasks
		[Bindable]
		public var tasks:ArrayCollection = new ArrayCollection();

		public function LocalData()
		{
		}

		public function addCategory( category:CategoryVO ):CategoryVO
		{
			var localc:CategoryVO = getCategory( category.id );
			if ( localc == null )
			{
				categories.addItem( category );
				return category;
			}
			else
			{
				localc.name = category.name;
				return localc;
			}
		}

		public function addProject( project:ProjectVO ):ProjectVO
		{
			var localp:ProjectVO = getProject( project.id );
			if ( localp == null )
			{
				projects.addItem( project );
				return project;
			}
			else
			{
				localp.name = project.name;
				return localp;
			}
		}

		public function addTask( task:TaskVO ):TaskVO
		{
			// get local versions of project and category
			var p:ProjectVO = addProject( task.project );
			var c:CategoryVO = addCategory( task.category );

			// set the task project and category to the local version
			task.project = p;
			task.category = c;
			
			// add category and project to each other
			if ( ArrayUtil.getItemIndex( c, p.children ) == -1 )
			{
				p.children.push(c);
			}
			if ( ArrayUtil.getItemIndex( task, c.children ) == -1 )
			{
				c.children.push(task);
			}
			
			var localt:TaskVO = getTask( task.id );
			if ( localt == null )
			{
				tasks.addItem( task );
				return task;
			}
			else
			{
				localt.project = task.project;
				localt.category = task.category;
				localt.completed = task.completed;
				localt.due_date = task.due_date;
				localt.description = task.description;	
				return localt;
			}
		}

		public function getProject( id:int ):ProjectVO
		{
			for each ( var p:ProjectVO in projects )
			{
				if (p.id == id) { return p; }
			}
			return null;
		}

		public function getCategory( id:int ):CategoryVO
		{
			for each ( var c:CategoryVO in categories )
			{
				if (c.id == id) { return c; }
			}
			return null;
		}

		public function getTask( id:int ):TaskVO
		{
			for each ( var t:TaskVO in tasks )
			{
				if (t.id == id) { return t; }
			}
			return null;
		}
					
	}
}